package cn.hcbycloud.auth.service;

import cn.hcbycloud.auth.bo.RoleBO;
import cn.hcbycloud.auth.mapper.RoleMapper;
import cn.hcbycloud.auth.model.Role;
import cn.hcbycloud.common.core.utils.ObjectUtils;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 角色表
 *
 * @author gaoheng
 * @date 2022-01-22 00:22:15
 */
@Service
@AllArgsConstructor
public class RoleService extends ServiceImpl<RoleMapper, Role> {
    private RoleMapper roleMapper;

    /**
     * 根据角色编码列表获取角色对象列表
     *
     * @param roleCodes
     * @param tenantId
     * @return
     */
    public List<RoleBO> getRolesByCodes(List<String> roleCodes, String tenantId) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.in("role_code", roleCodes).eq("tenant_id", tenantId);
        List<Role> roles = roleMapper.selectList(wrapper);
        List<RoleBO> roleBOList = CollUtil.newArrayList();
        roles.forEach(item -> {
            RoleBO roleBO = new RoleBO();
            roleBO.setRoleId(item.getId());
            roleBO.setRoleCode(item.getRoleCode());
            roleBO.setRoleName(item.getRoleName());
            roleBOList.add(roleBO);
        });
        return roleBOList;
    }

    public Set<String> getRoleCodesByUserId(String userId,String tenantId) {
        return roleMapper.selectRoleCodesByUserId(userId, tenantId);
    }

    /**
     * 添加角色信息
     *
     * @param roleBo
     * @param tenantId
     * @return
     */
    public String addRoleInfo(RoleBO roleBo, String tenantId) {
        Role role = null;
        try {
            role = ObjectUtils.cloneObject(roleBo, Role.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        role.preInsert();
        role.setTenantId(tenantId);
        roleMapper.insert(role);
        return role.getId();
    }
}
